package com.tmt.im.manager.interfaces.impl;

import com.tmt.data.jpa.enums.SMSCodeType;
import com.tmt.data.jpa.interfaces.ISMSCodeStorage;
import com.tmt.springboot.common.annotation._ReflectInvoked;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.data.redis.core.RedisTemplate;

import java.text.MessageFormat;
import java.time.Duration;

/**
 * 验证码存储器实现类
 *
 * @Description TODO
 * @Author wuyi
 * @Date 2024/8/5 23:55
 * @Version 1.0
 **/
@_ReflectInvoked("本类被反射调用")
public class SMSCodeStorage implements ISMSCodeStorage, ApplicationContextAware {

    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public boolean save(SMSCodeType type, String mobile, String code, Duration expireTime) {
        redisTemplate.opsForValue().set(MessageFormat.format("{0}_{1}", type.name(), mobile), code, expireTime);
        return true;
    }

    @Override
    public String load(SMSCodeType type, String mobile) {
        return (String) redisTemplate.opsForValue().get(MessageFormat.format("{0}_{1}", type.name(), mobile));
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        redisTemplate = applicationContext.getBean("customizedRedisTemplate", RedisTemplate.class);
    }
}
